import axios from 'axios';
import {
	Message
} from 'element-ui'
import {
	getCookie
} from '@/utils/util'
const STR = '方法不是 GET 或 POST 请注意大写！'
const INSTANCE = axios.create({
	timeout: 0
})

INSTANCE.interceptors.request.use(
	config => {
		config.headers.authorization = getCookie('token') || '';
		return config
	},
	error => {
		Message.error(error);
		return Promise.reject(error)
	}
)
INSTANCE.interceptors.response.use(
	response => {
		if (response.data.code == 200) {
			return response
		} else {
			Message.error(response.data.message)
			return Promise.reject('error')
		}
	}, error => {
		Message.error(error);
		return Promise.reject(error)
	})


// formData
const reqData = (method, url, dataJson) => {
	let data = '',
		params = ''
	if (method == 'POST') {
		data = dataJson
	} else if (method == 'GET') {
		params = dataJson
	} else {
		Message.error(STR)
		return true
	}
	return INSTANCE({
		method,
		url,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		data,
		params,
		traditional: true,
		transformRequest: [
			function(data) {
				let ret = ''
				for (let it in data) {
					ret +=
						encodeURIComponent(it) +
						'=' +
						encodeURIComponent(data[it]) +
						'&'
				}
				return ret
			}
		]
	});
};
// JSON
const reqJson = (method, url, dataJson) => {
	let data = '',
		params = ''
	if (method == 'POST') {
		data = dataJson
	} else if (method == 'GET') {
		params = dataJson
	} else {
		Message.error(STR)
		return true
	}
	return INSTANCE({
		method,
		url,
		headers: {
			'Content-Type': 'application/json'
		},
		data,
		params,
		traditional: true,
	});
};

// 不走验证
const noRlueJson = (method, url, dataJson, responseType) => {
	let data = '',
		params = ''
	if (method == 'POST') {
		data = dataJson
	} else if (method == 'GET') {
		params = dataJson
	} else {
		Message.error(STR)
		return true
	}
	return axios({
		method,
		url,
		headers: {
			'Content-Type': 'application/json',
			'authorization': getCookie('token') || ''
		},
		data,
		params,
		responseType,
		traditional: true,
	});
};
// 不走验证
const noRlueData = (method, url, dataJson, responseType) => {
	let data = '',
		params = ''
	if (method == 'POST') {
		data = dataJson
	} else if (method == 'GET') {
		params = dataJson
	} else {
		Message.error(STR)
		return true
	}
	return axios({
		method,
		url,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		data,
		params,
		responseType,
		traditional: true,
		transformRequest: [
			function(data) {
				let ret = ''
				for (let it in data) {
					ret +=
						encodeURIComponent(it) +
						'=' +
						encodeURIComponent(data[it]) +
						'&'
				}
				return ret
			}
		]
	});
};

export {
	reqData,
	reqJson,
	noRlueJson,
	noRlueData
}
